#include "applicationconnector.h"

#include <QJsonDocument>
#include <QJsonObject>


#include "socket.h"


ApplicationConnector::ApplicationConnector(Socket *clientSocket, QObject *parent) : QObject(parent)
{
    p_client = clientSocket;
    QObject::connect(p_client, SIGNAL(dataReceived(QByteArray)), this, SLOT(processClientData(QByteArray)));
}



void ApplicationConnector::connectApplication(int auid, Socket *socket)
{
    v_auidApplicationMap.insert(auid, socket);
    v_applicationAuidMap.insert(socket, auid);
    QObject::connect(socket, SIGNAL(dataReceived(QByteArray)), this, SLOT(processApplicationData(QByteArray)));
}



// SLOTS


void ApplicationConnector::processClientData(QByteArray data)
{
    //Socket *client = static_cast<Socket*>(sender());
    QJsonDocument doc = QJsonDocument::fromJson(data);

    QJsonObject obj = doc.object();
    if(!obj.contains("auid"))
        return;

    Socket *app = v_auidApplicationMap.value((int)obj.value("auid").toDouble());
    obj.remove("auid");
    doc.setObject(obj);

    app->write(doc.toJson());
}



void ApplicationConnector::processApplicationData(QByteArray data)
{
    Socket *applicationSocket = static_cast<Socket*>(sender());
    QJsonDocument doc = QJsonDocument::fromJson(data);

    QJsonObject obj = doc.object();
    int auid = v_applicationAuidMap.value(applicationSocket);
    obj.insert("auid", QJsonValue::fromVariant(QVariant(auid)));

    doc.setObject(obj);
    p_client->write(doc.toJson());
}
